package middleware

import (
	"fitness/go-admin/internal/repository"
	"fitness/go-admin/pkg/errcode"
	"fitness/go-admin/pkg/response"

	"github.com/gin-gonic/gin"
)

// AdminAuth 管理员权限验证中间件
func AdminAuth(userRepo repository.UserRepository) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 先通过Auth()中间件获取userId
		userID, exists := c.Get("userId")
		if !exists {
			response.Error(c, errcode.Unauthorized, "")
			c.Abort()
			return
		}

		// 查询用户信息
		user, role, err := userRepo.GetUserWithRole(userID.(uint))
		if err != nil {
			response.Error(c, errcode.UserNotFound, "用户不存在")
			c.Abort()
			return
		}

		// 检查用户状态
		if user.Status == 0 {
			response.Error(c, errcode.UserDisabled, "账号已被禁用")
			c.Abort()
			return
		}

		// 检查是否为管理员
		if role == nil || role.Code != "admin" {
			response.Error(c, errcode.PermissionDenied, "需要管理员权限")
			c.Abort()
			return
		}

		c.Next()
	}
}
